package com.ruoyi.system.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class OSSImageUpload {
    // OSS连接参数
    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tBeagSeMrJje1pf7LCj";
    private static final String ACCESS_KEY_SECRET = "X85WnvwbcFm3hPumcwh1GWxgXnBREa";
    private static final String BUCKET_NAME = "aoba-pic";

    public String uploadImage(String localFilePath, String ossKey) {
        // 1. 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 2. 读取本地图片为输入流
            InputStream inputStream = new java.io.FileInputStream(localFilePath);

            // 3. 上传图片到OSS（参数：Bucket名、OSS存储路径、输入流）
            ossClient.putObject(BUCKET_NAME, ossKey, inputStream);

            // 4. 生成图片访问URL（公开Bucket可直接访问，私有Bucket需签名URL）
            return "https://" + BUCKET_NAME + "." + ENDPOINT.replace("https://", "") + "/" + ossKey;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 5. 关闭客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public String uploadImage(MultipartFile file, String category) {
        if (file == null || file.isEmpty()) {
            return null;
        }
        
        String ossKey = generateOssKey(file.getOriginalFilename(), category);
        return uploadMultipartFile(file, ossKey);
    }

    private String uploadMultipartFile(MultipartFile file, String ossKey) {
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(BUCKET_NAME, ossKey, inputStream);
            return "https://" + BUCKET_NAME + "." + ENDPOINT.replace("https://", "") + "/" + ossKey;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public String generateOssKey(String originalFileName, String category) {
        String timestamp = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String randomStr = UUID.randomUUID().toString().substring(0, 8);
        String fileExt = "";
        
        if (originalFileName != null && originalFileName.contains(".")) {
            fileExt = originalFileName.substring(originalFileName.lastIndexOf("."));
        }
        
        return category + "/" + timestamp + "/" + randomStr + fileExt;
    }
}
